package com.shaoshaohuo.app.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.Address;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.DefaultAddressEntity;
import com.shaoshaohuo.app.entity.GoodUnits;
import com.shaoshaohuo.app.entity.cart.EcCartOrder;
import com.shaoshaohuo.app.entity.cart.EcCartOrderResponse;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.AddressManagerActivity;
import com.shaoshaohuo.app.ui.ec.PayEcActivity;
import com.shaoshaohuo.app.ui.ec.SupplyDetailActivity;
import com.shaoshaohuo.app.utils.AreaUtil;
import com.shaoshaohuo.app.utils.StringHelper;
import com.shaoshaohuo.app.utils.StringUtil;
import com.shaoshaohuo.app.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 电商直接下单，弹出窗口
 * 
 * @author YinSF
 * @createDate 2015-11-11
 */
public class EcCreateOrderPopupWindow extends PopupWindow implements OnClickListener {
	private View contentView;
	private TextView mContactNameEdit;
	private TextView mContactPhoneEdit;
	private TextView mRecivAddressText;
	private EditText mBuyCountEdit;
	private FragmentActivity mContext;
	private Address address;
	private String supplyid;
	private String unit;
	private boolean isUnitText = true;//默认显示唯一单位
	private TextView mUnitText;//唯一单位
	private Spinner mUnitSpinner;//多选单位
	private ArrayAdapter<String> adapter;
	private ProgressDialog progressDialog;
	
	private String cartPurchaseQuantities;//购物车采购数量
	private String cartUnits;//购物车采购数量
	
	private List<String> list = new ArrayList<String>();
	private Button nextButton;
	
	private boolean isForCart = false;
	private LinearLayout layoutBuyQuantity;

	/** 输入框小数的位数*/
	private static final int DECIMAL_DIGITS = 2;
	
	public EcCreateOrderPopupWindow(FragmentActivity context, boolean isForCart) {
		super(context);
		mContext = context;
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		contentView = inflater.inflate(R.layout.popwindow_order, null);
		setContentView(contentView);
		this.isForCart = isForCart;
		progressDialog = new ProgressDialog(mContext);
		WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display display = windowManager.getDefaultDisplay();
		Point p = new Point();
		display.getSize(p);
		//设置SelectPicPopupWindow弹出窗体的宽  
        this.setWidth(LayoutParams.MATCH_PARENT);  
        //设置SelectPicPopupWindow弹出窗体的高  
        this.setHeight(LayoutParams.WRAP_CONTENT);  
		// 设置SelectPicPopupWindow弹出窗体可点击  
        this.setFocusable(true);  
        this.setOutsideTouchable(true);  
        // 实例化一个ColorDrawable颜色为半透明  
        ColorDrawable dw = new ColorDrawable(0xb0ff0000);  
        // 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作  
        this.setBackgroundDrawable(dw);  
        setAnimationStyle(android.R.style.Animation_Dialog);  
        
        setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        // 设置SelectPicPopupWindow弹出窗体动画效果  
//        this.setAnimationStyle(R.style.AnimationPreview);  
        initView();
        initListeners();
	}

	private void requestData() {
		progressDialog.startLoadingDialog();
		RequestService.getInstance().getDefaultAddress(contentView.getContext(), DefaultAddressEntity.class, new RequestListener() {
			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				progressDialog.dismissLoadingDialog();
				if (resultData.isOk()) {
					DefaultAddressEntity addressEntity = (DefaultAddressEntity) resultData;
					if (addressEntity.getData() != null) {
						setAddress(addressEntity.getData());
					}
				}

			}

			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				progressDialog.dismissLoadingDialog();
				//TODO 这里去掉提示信息，是因为当用户未设置默认地址
//				showToast(msg);
			}
		});		
	}

	private void initListeners() {
		mRecivAddressText.setOnClickListener(this);
		mContactNameEdit.setOnClickListener(this);
		mContactPhoneEdit.setOnClickListener(this);
		nextButton.setOnClickListener(this);

		/**
		 *  设置小数位数控制
		 */
		InputFilter lengthfilter = new InputFilter() {
			public CharSequence filter(CharSequence source, int start, int end,
									   Spanned dest, int dstart, int dend) {
				// 删除等特殊字符，直接返回
				if ("".equals(source.toString())) {
					return null;
				}
				String dValue = dest.toString();
				String[] splitArray = dValue.split("//.");
				if (splitArray.length > 1) {
					String dotValue = splitArray[1];
					int diff = dotValue.length() + 1 - DECIMAL_DIGITS;
					if (diff > 0) {
						return source.subSequence(start, end - diff);
					}
				}
				return null;
			}
		};
		mBuyCountEdit.setFilters(new InputFilter[]{lengthfilter});
		mBuyCountEdit.addTextChangedListener(new TextWatcher() {

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (!StringUtil.isEmpty(s)) {
					String[] strArr = s.toString().split(".");
					if (strArr.length > 1 && strArr[1] != null && strArr[1].length() > 2) {
						s = strArr[0] + strArr[1].substring(0, 2);
					}
				}
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (!StringUtil.isEmpty(s.toString())) {
					String[] strArr = s.toString().split("[.]");
					if (strArr.length > 1 && strArr[1] != null && strArr[1].length() > 2) {
						s.clear();
						s.append(strArr[0]);
						s.append(".");
						s.append(strArr[1].substring(0, 2));
						mBuyCountEdit.setText(s);
					}
				}
			}
		});
	}

	private void initView() {
		layoutBuyQuantity = (LinearLayout) contentView.findViewById(R.id.layout_buy_quantity);
		if (isForCart) {
			layoutBuyQuantity.setVisibility(View.GONE);
		}
		mBuyCountEdit = (EditText) contentView.findViewById(R.id.edittext_buy_count);
		mContactNameEdit = (TextView) contentView.findViewById(R.id.textview_contact_name);
		mContactPhoneEdit = (TextView) contentView.findViewById(R.id.textview_contact_phone);
		mRecivAddressText = (TextView) contentView.findViewById(R.id.textview_recev_address);
		mUnitText = (TextView) contentView.findViewById(R.id.textview_buy_unit);
		mUnitSpinner = (Spinner) contentView.findViewById(R.id.textview_buy_unit_relation);
		nextButton = (Button) contentView.findViewById(R.id.button_next);
	}

	@Override
	public void showAtLocation(View parent, int gravity, int x, int y) {
		requestData();
		nextButton.setEnabled(true);
		super.showAtLocation(parent, gravity, x, y);
		backgroundAlpha(0.3f);
	}

	public void setAddress(Address address) {
		this.address = address;
		mRecivAddressText.setText(AreaUtil.getAreaFullname(address.getCityid()) + address.getAddress());
		mContactPhoneEdit.setText(address.getReceiver_phone());
		mContactNameEdit.setText(address.getReceiver_name());
	}

	/**
	 * 设置添加屏幕的背景透明度
	 * @param bgAlpha
	 */
	public void backgroundAlpha(float bgAlpha)
	{
		if (mContext instanceof Activity) {
			Activity activity = (Activity) mContext;
			WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
			lp.alpha = bgAlpha; //0.0-1.0
			activity.getWindow().setAttributes(lp);
		}
	}

	/**
	 * 设置产品单位
	 * @param unit
	 */
	public void setUnit(String unit) {
		this.unit = unit;
		isUnitText = GoodUnits.isUniqueUnit(unit);
		if (isUnitText) {
			mUnitText.setVisibility(View.VISIBLE);
			mUnitSpinner.setVisibility(View.GONE);
			mUnitText.setText(unit);
		} else {
			mUnitText.setVisibility(View.GONE);
			mUnitSpinner.setVisibility(View.VISIBLE);
			list.clear();
			List<String> unitList = Arrays.asList(GoodUnits.getAllRelationUnits(unit));
			list.addAll(unitList);
			//第二步：为下拉列表定义一个适配器，这里就用到里前面定义的list。    
	        adapter = new ArrayAdapter<String>(mUnitSpinner.getContext(), android.R.layout.simple_spinner_item, list);    
	        //第三步：为适配器设置下拉列表下拉时的菜单样式。    
	        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
	        //第四步：将适配器添加到下拉列表上    
	        mUnitSpinner.setAdapter(adapter);    
	        mUnitSpinner.setSelection(unitList.indexOf(unit));
		}
	}

	@Override
	public void dismiss() {
		super.dismiss();
		backgroundAlpha(1);
	}

	public void showToast(String text) {
        ToastUtil.toast(text);
    }
	
    private void toPayOrder() {
    	EcCartOrder supplyOrder = new EcCartOrder();

		String num = mBuyCountEdit.getText().toString().trim();
		if (!isForCart) {
			if (TextUtils.isEmpty(num)) {
				showToast("请输入购买数量");
				return;
			}
		}

		String realname = mContactNameEdit.getText().toString().trim();
		String mobile = mContactPhoneEdit.getText().toString().trim();
		if (TextUtils.isEmpty(realname)) {
			showToast("请输入联系人姓名");
			return;
		}
		if (TextUtils.isEmpty(mobile)) {
			showToast("请输入联系人电话");
			return;
		}
		if (!StringHelper.isPhoneNumber(mobile)) {
			showToast("请输入合格的联系人电话");
			return;
		}


		supplyOrder.setIds(getSupplyid());
		if (isForCart) {
			supplyOrder.setQuantitys(getCartPurchaseQuantities());
			supplyOrder.setUnits(getCartUnits());
		} else {
			supplyOrder.setQuantitys(num);
			if (isUnitText) {
				supplyOrder.setUnits(mUnitText.getText().toString());
			} else {
				supplyOrder.setUnits(mUnitSpinner.getSelectedItem().toString());
			}
		}
		supplyOrder.setReceivingaddressid(address.getId());
		nextButton.setEnabled(false);
		progressDialog.startLoadingDialog();
		RequestService.getInstance().saveEcCartOrder(mContext, supplyOrder, EcCartOrderResponse.class,
				new RequestListener() {

					@Override
					public void onSuccess(int requestCode, BaseEntity resultData) {
						progressDialog.dismissLoadingDialog();
						if (resultData.isOk()) {
							EcCartOrderResponse entity = (EcCartOrderResponse) resultData;
							Intent intent = new Intent(mContext, PayEcActivity.class);
							intent.putExtra(ExtraName.orderid, entity.getData().getOrderids());
							intent.putExtra(ExtraName.totalPrice, Double.parseDouble(entity.getData().getTotalMoney()));
							intent.putExtra(ExtraName.action, PayEcActivity.PAY_ACTION_SUPPLY);
							mContext.startActivity(intent);
							dismiss();
						} else {
							// PlaceSupplyOrderEntity entity = (PlaceSupplyOrderEntity)
							// resultData;
							showToast(resultData.getMsg());
							nextButton.setEnabled(true);
						}
					}

					@Override
					public void onFailed(int requestCode, Exception error, String msg) {
						progressDialog.dismissLoadingDialog();
						showToast(mContext.getString(R.string.please_check_network));
						nextButton.setEnabled(true);
					}
				});
    }

	public String getCartPurchaseQuantities() {
		return cartPurchaseQuantities;
	}

	public void setCartPurchaseQuantities(String cartPurchaseQuantities) {
		this.cartPurchaseQuantities = cartPurchaseQuantities;
	}

	public String getSupplyid() {
		return supplyid;
	}

	public void setSupplyid(String supplyid) {
		this.supplyid = supplyid;
	}

	public String getCartUnits() {
		return cartUnits;
	}

	public void setCartUnits(String cartUnits) {
		this.cartUnits = cartUnits;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.textview_contact_name:
		case R.id.textview_contact_phone:
		case R.id.textview_recev_address:
			Intent intent = new Intent(mContext, AddressManagerActivity.class);
			intent.putExtra(ExtraName.isForResult, true);
			mContext.startActivityForResult(intent, SupplyDetailActivity.REQUEST_CODE_ADDRESS);
			break;
		case R.id.button_next:
			toPayOrder();
			break;
		default:
			break;
		}
	}
	
}
